package com.hejun.seckillconsumer.consumer;

import com.hejun.seckillconsumer.dao.PurchaseRecordMapper;
import com.hejun.seckillconsumer.domain.Products;
import com.hejun.seckillconsumer.domain.PurchaseRecord;
import com.hejun.seckillconsumer.service.impl.ProductsServiceImpl;
import com.hejun.seckillconsumer.service.impl.PurchaseRecordServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Component
@Slf4j
public class SecKillConsumer {
    @Autowired
    ProductsServiceImpl productsService;
    @Autowired
    PurchaseRecordServiceImpl purchaseRecordService;
    @Transactional
    @RabbitListener(queues = "secKill_test_queue")
    public void show(Map map) {
        Integer userId = (Integer) map.get("userId");
        Integer productsId = (Integer) map.get("productsId");
        Long time = (Long) map.get("time");

        log.info("用户 {}正在抢购，点击时间:{}，抢购商品:{}", userId, time, productsId);

        Products product = productsService.getById(productsId);

        if (product.getTotal() > 0) {
            product.setTotal(product.getTotal() - 1);
            if (productsService.saveOrUpdate(product)) {
                PurchaseRecord purchaseRecord = new PurchaseRecord();
                purchaseRecord.setProductsId(productsId);
                purchaseRecord.setUserId(userId);
                purchaseRecordService.saveOrUpdate(purchaseRecord);
                log.info("用户：{}抢购商品：{}成功", userId, product);
            } else {
                log.info("用户：{}抢购商品：{}失败", userId, product);
            }
        } else {
            log.info("用户：{}抢购商品：{}失败", userId, product);
        }
    }
}
